<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\controller\member;

use buwang\facade\WechatPay;
use app\common\model\member\Wallet;
use app\common\model\member\WalletBill;
use app\common\model\member\WalletRecharge;
use buwang\base\MemberBaseController;
use Exception;
use think\facade\Log;

class Notify extends MemberBaseController
{

    /**
     * 服务商统一回调通知
     * @return void
     */
    public function index()
    {
        try {
            $response = WechatPay::doPay()->handlePaidNotify(function ($message, $fail) {
                //记录回调信息至日志
                //trace(json_encode($message), 'notify');
                //file_put_contents('notify.txt', json_encode($message) . PHP_EOL, FILE_APPEND);

                $rel = WalletRecharge::where(['order_sn' => $message['out_trade_no'], 'state' => 0])->find();
                if (empty($rel)) return true;

                if ($message['return_code'] === 'SUCCESS' && $message['result_code'] === 'SUCCESS') {
                    $ispay = WechatPay::doPay()->order->queryByOutTradeNumber($rel->order_sn);

                    if ($ispay['return_code'] === 'SUCCESS' && $ispay['result_code'] === 'SUCCESS' && $ispay['trade_state'] === 'SUCCESS'
                        && $ispay['total_fee'] == $rel->money * 100) {
                        $rel->state = 1;
                        $rel->update_time = time();
                        $rel->transaction_id = $ispay['transaction_id'];;
                        $rel->save();

                        Wallet::changeMoney($rel->member_id, 'recharge', $ispay['total_fee'] / 100, '微信充值');
                    }
                }
                return $fail('通信失败,请稍后再通知我');
            });
            $response->send();
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
    }
}